<template>
  <a-drawer
    v-model:visible="visible"
    class="custom-class"
    :title="formState.id ? '编辑' : '新增'"
    :mask-closable="false"
    placement="right"
    width="500px"
    @close="close"
  >
    <a-form
      ref="formRef"
      :model="formState"
      :rules="formRules"
      :label-col="{ span: 3 }"
    >
      <a-form-item label="名称" name="name">
        <a-input v-model:value="formState.name" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="字典值" name="value">
        <a-input v-model:value="formState.value" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="父级" name="parentId">
        <a-select
          v-model:value="formState.parentId"
          placeholder="不选默认为根节点"
          allow-clear
          :options="dictList"
          :field-names="{ label: 'name', value: 'id' }"
          style="width: 200px; text-align: left"
        >
        </a-select>
      </a-form-item>
      <!-- <a-form-item label="可用" name="status">
        <a-switch
          v-model:checked="formState.status"
          checked-value="1"
          un-checked-value="0"
        />
      </a-form-item> -->
      <a-form-item label="备注">
        <a-textarea v-model:value="formState.remark" />
      </a-form-item>
      <a-form-item :wrapper-col="{ span: 21, offset: 3 }">
        <a-button
          type="primary"
          @click.prevent="onSubmit"
          style="margin-right: 12px"
        >
          保存
        </a-button>
        <a-button @click="close">取消</a-button>
      </a-form-item>
    </a-form>
  </a-drawer>
</template>
<script setup>
import { add, update } from "@/api/dict"
import { ref, reactive, toRaw, onMounted, computed, watch } from "vue"
import { selectList as selectDictList } from "@/api/dict"

const props = defineProps({
  visible: Boolean,
  current: Object,
})
const emit = defineEmits(["update:visible", "update:current", "query"])

const dictList = ref([])

const formRef = ref()
const formState = ref({
  id: "",
  name: "",
  status: "1",
  summary: "",
})
const formRules = reactive({
  name: [{ required: true, message: "分类名称不能为空!" }],
  value: [{ required: true, message: "字典值不能为空!" }],
})

const close = () => {
  emit("update:current", null)
  emit("update:visible", false)
}

const onSubmit = () => {
  formRef.value
    .validate()
    .then(async () => {
      const func = (e) => (!formState.value.id ? add(e) : update(e))
      const { data, code } = await func(formState.value)
      if (code !== 300) return
      emit("query")
      close()
    })
    .catch((err) => {
      console.log("error", err)
    })
}

/** 获取字典 */
const getDictList = async () => {
  const { data, code } = await selectDictList()
  if (code !== 200) return
  dictList.value = data
}

onMounted(() => {
  getDictList()
})

watch(
  () => props.current,
  (e) => {
    e ? Object.assign(formState.value, props.current) : (formState.value = {})
  },
  { deep: true }
)
</script>
<style lang="less" scoped></style>
